<?
/*--------------------------
	file:	token.class
	intro:	令牌创建和验证类
--------------------------*/

class Helper_Token {
	public $check_token;
	public $check_referer;
	
	function __construct() {
		$this->check_token = TRUE;
		$this->check_referer = TRUE;
	}
	
	function create($html = false) {
		$token = Mid::helper ( 'guid' )->toString ();
		if ($html) {
			return '<input type=hidden name="token" value="' . $token . '" />';
		}
		return $token;
	}
	
	function check() {
		$token = $_REQUEST ['token'];
		$tokenArr = isset ( $_SESSION ['token'] ) ? $_SESSION ['token'] : array ();
		
		if (! $token && $this->check_token == TRUE) {
			return false;
		}
		if (! empty ( $tokenArr ) && in_array ( $token, $tokenArr )) {
			return false;
		} else {
			$token != '' && $_SESSION ['token'] [] = $token;
		}
		
		if ($this->check_referer === TRUE && $_SERVER ['HTTP_REFERER']) {
			$host = $_SERVER ['HTTP_HOST'];
			$referurl = $_SERVER ['HTTP_REFERER'];
			
			if($this->getServer($host)!=$this->getServer($referurl)){
				return false;
			}
		}
		return true;
	}
	
	static function getServer($url) {
		$pattern = "/[\w-]+\.(com|net|org|gov|cc|biz|info|cn)(\.(cn|hk))*/";
		@preg_match ( $pattern, $url, $matches );
		if (count ( $matches ) > 0) {
			return $matches [0];
		} else {
			$rs = parse_url ( $url );
			$main_url = $rs ["host"];
			if (! strcmp ( long2ip ( sprintf ( "%u", ip2long ( $main_url ) ) ), $main_url )) {
				return $main_url;
			} else {
				$arr = explode ( ".", $main_url );
				$count = count ( $arr );
				$endArr = array ("com", "net", "org", "3322" ); //com.cn  net.cn 等情况
				if (in_array ( $arr [$count - 2], $endArr )) {
					$domain = $arr [$count - 3] . "." . $arr [$count - 2] . "." . $arr [$count - 1];
				} else {
					$domain = $arr [$count - 2] . "." . $arr [$count - 1];
				}
				return $domain;
			}
		}
	}
}
?>